package com.example.micro.netty.server.nettygroup;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

public class GroupChatClient {

    //属性
    private final String host;
    private final int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws InterruptedException {

        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            //得到pipeline
                            ChannelPipeline channelPipeline = socketChannel.pipeline();

                            //加入相关handler
                            channelPipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                            channelPipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

                            channelPipeline.addLast(new GroupChatClientHandler());

                        }

                    });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            Channel channel = channelFuture.channel();
            this.sendData(channel);
        } finally {
            eventExecutors.shutdownGracefully();
        }

    }

    private void sendData(Channel channel) {
        System.out.println("------" + channel.localAddress() + "-------");
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            //通过channel发送到服务端
            channel.writeAndFlush(msg + "\n");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatClient("127.0.0.1", 7000).run();
    }

}
